import uuid
from datetime import datetime

from flask_sqlalchemy import SQLAlchemy as _SQLAlchemy
from sqlalchemy import Column, SmallInteger, String, DateTime
from contextlib import contextmanager


class SQLAlchemy(_SQLAlchemy):
    """
        自动commit装饰器
        异常时自动回滚
    """

    @contextmanager
    def auto_commit(self):
        try:
            yield
            self.session.commit()
        except Exception as e:
            db.session.rollback()
            raise e


db = SQLAlchemy()


class BaseModel(db.Model):
    __abstract__ = True
    id = Column(String(40), primary_key=True, unique=True)
    create_time = Column(DateTime)

    # __mapper_args__ = {
    #     "order_by": create_time
    # }

    def __getitem__(self, item):
        return getattr(self, item)

    def __init__(self):
        self.create_time = datetime.now()
        self.id = str(uuid.uuid4()).replace('-', '')

    # 传入dict设置所有匹配的属性
    def set_attrs(self, attrs_dict):
        for key, value in attrs_dict.items():
            if hasattr(self, key) and key != 'id':
                setattr(self, key, value)
